const Router = require('koa-router')
const { TableConfig, TableColumn, TableAction, sequelize } = require('../models')
const auth = require('../middleware/auth')

const router = new Router({ prefix: '/api/table-config' })

// 获取表格配置
router.get('/:table_id/config', auth.checkPermission('system:read'), async (ctx) => {
  try {
    const { table_id } = ctx.params

    const tableConfig = await TableConfig.findOne({
      where: { table_id, status: 'active' },
      include: [
        {
          model: TableColumn,
          as: 'columns',
          where: { status: 'active', visible: true },
          order: [['sort_order', 'ASC']],
          required: false
        }
      ]
    })

    if (!tableConfig) {
      ctx.status = 404
      ctx.body = {
        success: false,
        message: '表格配置不存在'
      }
      return
    }

    // 获取可用的操作
    const actions = await TableAction.findAll({
      where: { status: 'active' },
      order: [['created_at', 'ASC']]
    })

    ctx.body = {
      success: true,
      data: {
        config: tableConfig,
        actions: actions
      },
      message: '获取表格配置成功'
    }
  } catch (error) {
    console.error('获取表格配置失败:', error)
    ctx.status = 500
    ctx.body = {
      success: false,
      message: '获取表格配置失败',
      error: error.message
    }
  }
})

// 获取表格数据
router.get('/:table_id/data', auth.checkPermission('system:read'), async (ctx) => {
  try {
    const { table_id } = ctx.params
    const { 
      page = 1, 
      limit = 20, 
      search = '', 
      sort_field = 'id', 
      sort_order = 'DESC',
      filters = '{}' 
    } = ctx.query

    // 获取表格配置
    const tableConfig = await TableConfig.findOne({
      where: { table_id, status: 'active' }
    })

    if (!tableConfig) {
      ctx.status = 404
      ctx.body = {
        success: false,
        message: '表格配置不存在'
      }
      return
    }

    const tableName = tableConfig.table_name
    const offset = (page - 1) * limit
    
    // 构建查询条件
    let whereClause = ''
    let countQuery = `SELECT COUNT(*) as total FROM ${tableName}`
    let dataQuery = `SELECT * FROM ${tableName}`
    
    // 搜索条件
    if (search && tableConfig.searchable_columns) {
      const searchColumns = tableConfig.searchable_columns
      const searchConditions = searchColumns.map(col => `${col} LIKE :search`).join(' OR ')
      whereClause = ` WHERE (${searchConditions})`
      countQuery += whereClause
      dataQuery += whereClause
    }
    
    // 筛选条件
    try {
      const filterObj = JSON.parse(filters)
      if (Object.keys(filterObj).length > 0) {
        const filterConditions = Object.entries(filterObj)
          .map(([key, value]) => `${key} = :${key}`)
          .join(' AND ')
        
        if (whereClause) {
          whereClause += ` AND ${filterConditions}`
        } else {
          whereClause = ` WHERE ${filterConditions}`
        }
        
        countQuery = `SELECT COUNT(*) as total FROM ${tableName}${whereClause}`
        dataQuery = `SELECT * FROM ${tableName}${whereClause}`
      }
    } catch (e) {
      // 忽略筛选条件解析错误
    }
    
    // 排序和分页
    dataQuery += ` ORDER BY ${sort_field} ${sort_order} LIMIT ${limit} OFFSET ${offset}`
    
    // 查询参数
    const queryParams = {
      replacements: { 
        search: search ? `%${search}%` : '',
        ...JSON.parse(filters)
      },
      type: sequelize.QueryTypes.SELECT
    }

    // 获取总数
    const countResult = await sequelize.query(countQuery, queryParams)
    const total = countResult[0]?.total || 0

    // 获取数据
    const data = await sequelize.query(dataQuery, queryParams)

    ctx.body = {
      success: true,
      data: {
        list: data,
        pagination: {
          current: parseInt(page),
          pageSize: parseInt(limit),
          total: total,
          pages: Math.ceil(total / limit)
        }
      },
      message: '获取表格数据成功'
    }
  } catch (error) {
    console.error('获取表格数据失败:', error)
    ctx.status = 500
    ctx.body = {
      success: false,
      message: '获取表格数据失败',
      error: error.message
    }
  }
})

// 执行表格操作
router.post('/:table_id/action/:action_id', auth.checkPermission('system:write'), async (ctx) => {
  try {
    const { table_id, action_id } = ctx.params
    const { record_id, data } = ctx.request.body

    // 获取表格配置
    const tableConfig = await TableConfig.findOne({
      where: { table_id, status: 'active' }
    })

    if (!tableConfig) {
      ctx.status = 404
      ctx.body = {
        success: false,
        message: '表格配置不存在'
      }
      return
    }

    // 获取操作配置
    const action = await TableAction.findOne({
      where: { action_id, status: 'active' }
    })

    if (!action) {
      ctx.status = 404
      ctx.body = {
        success: false,
        message: '操作配置不存在'
      }
      return
    }

    const tableName = tableConfig.table_name

    // 根据操作类型执行相应操作
    let result
    switch (action_id) {
      case 'delete':
        await sequelize.query(
          `DELETE FROM ${tableName} WHERE id = :id`,
          {
            replacements: { id: record_id },
            type: sequelize.QueryTypes.DELETE
          }
        )
        result = { message: '删除成功' }
        break

      case 'activate':
        await sequelize.query(
          `UPDATE ${tableName} SET status = 'active' WHERE id = :id`,
          {
            replacements: { id: record_id },
            type: sequelize.QueryTypes.UPDATE
          }
        )
        result = { message: '启用成功' }
        break

      case 'deactivate':
        await sequelize.query(
          `UPDATE ${tableName} SET status = 'inactive' WHERE id = :id`,
          {
            replacements: { id: record_id },
            type: sequelize.QueryTypes.UPDATE
          }
        )
        result = { message: '禁用成功' }
        break

      default:
        ctx.status = 400
        ctx.body = {
          success: false,
          message: '不支持的操作类型'
        }
        return
    }

    ctx.body = {
      success: true,
      data: result,
      message: '操作执行成功'
    }
  } catch (error) {
    console.error('执行表格操作失败:', error)
    ctx.status = 500
    ctx.body = {
      success: false,
      message: '执行表格操作失败',
      error: error.message
    }
  }
})

// 获取所有表格配置列表
router.get('/list', auth.checkPermission('system:read'), async (ctx) => {
  try {
    const tableConfigs = await TableConfig.findAll({
      where: { status: 'active' },
      attributes: ['id', 'table_id', 'name', 'description', 'table_name'],
      order: [['created_at', 'ASC']]
    })

    ctx.body = {
      success: true,
      data: tableConfigs,
      message: '获取表格配置列表成功'
    }
  } catch (error) {
    console.error('获取表格配置列表失败:', error)
    ctx.status = 500
    ctx.body = {
      success: false,
      message: '获取表格配置列表失败',
      error: error.message
    }
  }
})

module.exports = router